import routerMap, { routerMapKeyList } from '@/router/routerMap'
import { useEffect } from 'react'
import {
  BrowserRouter,
  NavigateFunction,
  Route,
  Routes,
  useNavigate,
} from 'react-router-dom'
import IMenuVO from './model/vo/menu/IMenuVO'
import noLoginList from './router/noLoginList'
import { useAppDispatch } from './store'
import { setCurrentRouter } from './store/user/userSlice'
import appApi from './support'

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="" element={<LoadElement elementTemp="frame" />}>
          {/* 不用登录就可以访问的路由 ↓ */}
          {noLoginList.map((item, index) => (
            <Route
              key={index}
              path={item.path}
              element={
                <LoadElement
                  title={item.title}
                  elementTemp={item.elementTemp}
                />
              }
            ></Route>
          ))}
          <Route
            path="*"
            // 备注：这里不需要设置 title = '404'，exception404 里面进行单独设置
            element={<LoadElement elementTemp="exception404" />}
          ></Route>
        </Route>
      </Routes>
    </BrowserRouter>
  )
}

let AppNav: NavigateFunction
export function getAppNav() {
  return AppNav
}

interface ILoadElement {
  title?: string
  elementTemp: string
  menuInfo?: IMenuVO // 菜单信息
}

// 加载 element
function LoadElement(props: ILoadElement) {
  AppNav = useNavigate()

  if (props.title && appApi.type !== 1) {
    document.title = props.title // 修改标题
  }

  const appDispatch = useAppDispatch()

  useEffect(() => {
    appDispatch(
      setCurrentRouter(props.menuInfo?.id ? props.menuInfo : ({} as IMenuVO)) // 如果不存在 menuInfo的，需要设置为 {}
    ) // 设置当前路由信息
  }, [props.elementTemp])

  if (routerMapKeyList.includes(props.elementTemp)) {
    const Element = routerMap[props.elementTemp].elementTemp
    return <Element />
  }

  return null
}
